-- EnemySpawner.lua
-- 敌人生成器 - 完整的敌人系统实现

local EnemySpawner = {}
EnemySpawner.__index = EnemySpawner

function EnemySpawner.new(scene, playerEntity, sceneBounds)
    local instance = setmetatable({
        scene = scene,
        playerEntity = playerEntity,
        sceneBounds = sceneBounds or {
            left = 0,
            right = 2560,
            top = 1600,
            bottom = 0,
            width = 2560,
            height = 1600
        },
        
        -- 敌人移动系统
        enemyMovementSystem = nil,
        
        enemies = {},  -- 存储所有敌人
        enemyCount = 0,
        
        -- 敌人定义（符合空洞骑士/终焉莉莉丝风格）
        enemyDefinitions = {
            sword = {
                maxSpeed = 200,
                mass = 1,
                radius = 20,
                health = 100,
                maxHealth = 100,
                scale = 0.1,
                moveSpeed = 150,  -- 移动速度
                spinePath = "model/sword/sword",
                type = "sword"
            },
            archer = {
                maxSpeed = 150,
                mass = 1,
                radius = 18,
                health = 80,
                maxHealth = 80,
                scale = 0.1,
                moveSpeed = 120,
                spinePath = "model/archer/archer",
                type = "archer"
            },
            broadsword = {
                maxSpeed = 180,
                mass = 1.2,
                radius = 22,
                health = 120,
                maxHealth = 120,
                scale = 0.1,
                moveSpeed = 130,
                spinePath = "model/broadsword/broadsword",
                type = "broadsword"
            },
            boss = {
                maxSpeed = 250,
                mass = 2.0,
                radius = 40,
                health = 500,
                maxHealth = 500,
                scale = 0.2,
                moveSpeed = 180,
                spinePath = "model/boss/boss",
                type = "boss"
            }
        },
        
        -- 敌人生成位置缓存
        spawnPositions = {},
        
        debugMode = true
    }, EnemySpawner)
    
    -- 初始化敌人移动系统
    local EnemyMovementSystem = require("EnemyMovementSystem")
    instance.enemyMovementSystem = EnemyMovementSystem.new(instance.sceneBounds)
    
    return instance
end

-- 设置地面平台
function EnemySpawner:setGroundPlatforms(platforms)
    if self.enemyMovementSystem then
        self.enemyMovementSystem:setGroundPlatforms(platforms)
    end
end

-- 添加生成位置
function EnemySpawner:addSpawnPosition(position)
    table.insert(self.spawnPositions, position)
    return #self.spawnPositions
end

-- 清空生成位置
function EnemySpawner:clearSpawnPositions()
    self.spawnPositions = {}
end

-- 获取随机生成位置
function EnemySpawner:getRandomSpawnPosition()
    if #self.spawnPositions == 0 then
        -- 如果没有指定生成位置，使用默认位置
        return {
            x = math.random(self.sceneBounds.left + 100, self.sceneBounds.right - 100),
            y = math.random(self.sceneBounds.bottom + 200, self.sceneBounds.top - 200)
        }
    end
    
    local randomIndex = math.random(1, #self.spawnPositions)
    return self.spawnPositions[randomIndex]
end

-- 生成敌人（在指定位置）
function EnemySpawner:spawnEnemy(enemyType, position)
    local def = self.enemyDefinitions[enemyType]
    if not def then
        print("错误：未知的敌人类型: " .. enemyType)
        return nil
    end
    
    -- 创建敌人ID
    local enemyId = enemyType .. "_" .. tostring(self.enemyCount + 1)
    self.enemyCount = self.enemyCount + 1
    
    -- 创建敌人节点
    local Node = require("Node")
    local enemyNode = Node()
    enemyNode.x = position.x
    enemyNode.y = position.y
    
    -- 添加到场景
    if self.scene then
        self.scene:addChild(enemyNode)
    end
    
    -- 创建敌人实体数据
    local enemyData = {
        id = enemyId,
        enemyType = enemyType,
        position = {x = position.x, y = position.y},
        velocity = {x = 0, y = 0},
        maxSpeed = def.maxSpeed,
        mass = def.mass,
        radius = def.radius,
        health = def.health,
        maxHealth = def.maxHealth,
        isAlive = true,
        moveInput = 0,
        moveSpeed = def.moveSpeed,
        facingDirection = 1,
        lastDirection = 1,
        currentSpeed = 0,
        isGrounded = true,
        wasGrounded = true,
        aiState = "idle"
    }
    
    -- 注册到敌人移动系统
    local success = self.enemyMovementSystem:registerEntity({
        id = enemyId,
        position = {x = position.x, y = position.y},
        velocity = {x = 0, y = 0},
        maxSpeed = def.maxSpeed,
        mass = def.mass,
        radius = def.radius,
        facingDirection = 1,
        moveInput = 0,
        moveSpeed = def.moveSpeed,
        node = enemyNode
    })
    
    if not success then
        print("错误：注册敌人到移动系统失败")
        if enemyNode.parent then
            enemyNode:removeFromParent()
        end
        return nil
    end
    
    -- 创建动作系统
    local EnemyActionSystem = require("EnemyActionSystem")
    local actionSystem = EnemyActionSystem.new(enemyType, self.enemyMovementSystem)
    
    -- 创建Spine节点
    local spineNode = actionSystem:createSpineNode()
    if spineNode then
        actionSystem:setSpineNode(spineNode)
        actionSystem:setScale(def.scale)
        
        -- 设置动画映射
        local animationMap = {}
        if enemyType == "sword" then
            -- 剑士：普通攻击chop，冲锋三段动画，走路walk，空闲idle
            animationMap = {
                idle = "idle",
                walk = "walk",
                attack = "chop",
                dash1 = "dash1",
                dash2 = "dash2",
                dash3 = "dash3",
                hurt = "waiting"
            }
        elseif enemyType == "archer" then
            -- 弓箭手：普通攻击shoot，走路walk，空闲idle
            animationMap = {
                idle = "idle",
                walk = "walk",
                attack = "shoot",
                hurt = "waiting"
            }
        elseif enemyType == "broadsword" then
            -- 刀兵：攻击a1为举起刀，a1walk为拿刀走，a2为砍下，a3为技能连斩
            animationMap = {
                idle = "idle",
                walk = "walk",
                attack_a1 = "a1",
                attack_a1walk = "a1walk",
                attack_a2 = "a2",
                attack_a3 = "a3",
                hurt = "waiting"
            }
        elseif enemyType == "boss" then
            -- Boss：只有走路walk
            animationMap = {
                walk = "walk",
                attack_a1 = "a1",
                attack_a2 = "a2",
                dash1 = "dash1",
                dash2 = "dash2",
                dun = "dun",
                jump = "jump",
                fall = "fall",
                hurt = "waiting"
            }
        end
        
        actionSystem.animationMap = animationMap
        enemyNode:addChild(spineNode)
    end
    
    -- 创建AI系统（使用增强版）
    local EnemyAI = require("EnemyAI")
    local aiSystem = EnemyAI.new(enemyType, enemyData, self.playerEntity, self.enemyMovementSystem)
    
    -- 存储敌人信息
    local enemy = {
        id = enemyId,
        type = enemyType,
        data = enemyData,
        node = enemyNode,
        actionSystem = actionSystem,
        aiSystem = aiSystem,
        spineNode = spineNode,
        def = def
    }
    
    self.enemies[enemyId] = enemy
    
    if self.debugMode then
        print(string.format("生成敌人: %s, 位置: (%.1f, %.1f), 血量: %d/%d", 
            enemyId, position.x, position.y, enemyData.health, enemyData.maxHealth))
    end
    
    return enemy
end

-- 在随机位置生成敌人
function EnemySpawner:spawnRandomEnemy(enemyType)
    local spawnPos = self:getRandomSpawnPosition()
    return self:spawnEnemy(enemyType, spawnPos)
end

-- 批量生成敌人
function EnemySpawner:spawnEnemies(enemyList)
    local spawnedEnemies = {}
    
    for _, spawnInfo in ipairs(enemyList) do
        local enemy = self:spawnEnemy(spawnInfo.type, spawnInfo.position)
        if enemy then
            table.insert(spawnedEnemies, enemy)
        end
    end
    
    return spawnedEnemies
end

-- 在EnemySpawner类中添加以下方法：

-- 在关卡内随机生成敌人（基于切片）
function EnemySpawner:spawnEnemiesInLevel(levelManager, difficulty)
    difficulty = difficulty or 1
    local spawnedEnemies = {}
    
    -- 获取所有地面平台
    local groundPlatforms = levelManager:getGroundPlatforms()
    if #groundPlatforms == 0 then
        print("警告：没有地面平台，无法生成敌人")
        return spawnedEnemies
    end
    
    -- 敌人类型权重（根据难度调整）
    local enemyWeights = {
        sword = 40,
        archer = 30,
        broadsword = 20
    }
    
    -- 根据难度增加敌人数量
    local enemyCount = math.floor(10 * difficulty)
    
    for i = 1, enemyCount do
        -- 随机选择敌人类型
        local enemyType = self:getRandomEnemyType(enemyWeights)
        
        -- 在随机地面平台上生成敌人
        local platform = groundPlatforms[math.random(1, #groundPlatforms)]
        local spawnX = platform.x + math.random(50, platform.width - 50)
        local spawnY = platform.y + 200  -- 在平台上方200像素
        
        -- 确保生成位置在关卡边界内
        if spawnX >= self.sceneBounds.left and spawnX <= self.sceneBounds.right then
            local enemy = self:spawnEnemy(enemyType, {x = spawnX, y = spawnY})
            if enemy then
                table.insert(spawnedEnemies, enemy)
                
                -- 设置敌人攻击性
                self:setEnemyAggression(enemy.id, 1.0 + math.random() * 0.5)
                
                if self.debugMode then
                    print(string.format("关卡内生成敌人: %s, 位置=(%.1f,%.1f), 平台=%dx%d",
                        enemyType, spawnX, spawnY, platform.width, platform.height))
                end
            end
        end
    end
    
    return spawnedEnemies
end

-- 根据权重随机选择敌人类型
function EnemySpawner:getRandomEnemyType(weights)
    local totalWeight = 0
    for _, weight in pairs(weights) do
        totalWeight = totalWeight + weight
    end
    
    local randomValue = math.random() * totalWeight
    local currentWeight = 0
    
    for enemyType, weight in pairs(weights) do
        currentWeight = currentWeight + weight
        if randomValue <= currentWeight then
            return enemyType
        end
    end
    
    return "sword"  -- 默认返回剑士
end

-- 在特定切片生成敌人
function EnemySpawner:spawnEnemiesInTile(tileRow, tileCol, enemyList)
    local spawnedEnemies = {}
    
    -- 获取切片位置信息
    local LevelTileConfig = require("LevelTileConfig")
    local tileIndex = LevelTileConfig.getTileIndex(tileRow, tileCol)
    local tileInfo = LevelTileConfig.tilePositions[tileIndex]
    
    if not tileInfo then
        print(string.format("错误：切片 %d_%d 不存在", tileRow, tileCol))
        return spawnedEnemies
    end
    
    for _, enemyInfo in ipairs(enemyList) do
        -- 在切片内随机位置生成敌人
        local spawnX = tileInfo.x + math.random(100, LevelTileConfig.TILE_SIZE.width - 100)
        local spawnY = tileInfo.groundY + 200  -- 在地面上方
        
        local enemy = self:spawnEnemy(enemyInfo.type, {x = spawnX, y = spawnY})
        if enemy then
            table.insert(spawnedEnemies, enemy)
            
            if self.debugMode then
                print(string.format("切片 %d_%d 生成敌人: %s, 位置=(%.1f,%.1f)",
                    tileRow, tileCol, enemyInfo.type, spawnX, spawnY))
            end
        end
    end
    
    return spawnedEnemies
end

-- 更新所有敌人
function EnemySpawner:update(dt)
    -- 更新敌人移动系统
    if self.enemyMovementSystem then
        self.enemyMovementSystem:update(dt)
    end
    
    for enemyId, enemy in pairs(self.enemies) do
        if enemy.data.isAlive then
            -- 从移动系统获取最新位置和状态
            local entity = self.enemyMovementSystem:getEntity(enemyId)
            if entity then
                -- 更新敌人数据
                enemy.data.position.x = entity.position.x
                enemy.data.position.y = entity.position.y
                enemy.data.velocity.x = entity.velocity.x
                enemy.data.velocity.y = entity.velocity.y
                enemy.data.isGrounded = entity.isGrounded
                enemy.data.currentSpeed = entity.currentSpeed
                enemy.data.lastDirection = entity.lastDirection
                enemy.data.facingDirection = entity.lastDirection
                
                -- 更新节点位置
                enemy.node.x = entity.position.x
                enemy.node.y = entity.position.y
                
                -- 设置面向方向
                if enemy.actionSystem then
                    enemy.actionSystem:setFacingDirection(enemy.data.facingDirection == 1)
                end
            end
            
            -- 更新AI
            if enemy.aiSystem then
                enemy.aiSystem:update(dt, enemy.actionSystem)
            end
            
            -- 更新动作系统
            if enemy.actionSystem then
                enemy.actionSystem:update(dt)
            end
            
            -- 检查敌人是否死亡
            if enemy.data.health <= 0 then
                self:destroyEnemy(enemyId)
            end
        else
            -- 清理死亡敌人
            self:destroyEnemy(enemyId)
        end
    end
end

-- 销毁敌人
function EnemySpawner:destroyEnemy(enemyId)
    local enemy = self.enemies[enemyId]
    if not enemy then return end
    
    if self.debugMode then
        print("销毁敌人: " .. enemyId)
    end
    
    -- 清理动作系统
    if enemy.actionSystem then
        enemy.actionSystem:cleanup()
    end
    
    -- 从移动系统注销
    if self.enemyMovementSystem then
        self.enemyMovementSystem:unregisterEntity(enemyId)
    end
    
    -- 从场景移除节点
    if enemy.node and enemy.node.parent then
        enemy.node:removeFromParent()
    end
    
    -- 从列表中移除
    self.enemies[enemyId] = nil
end

-- 清除所有敌人
function EnemySpawner:clearAllEnemies()
    for enemyId, _ in pairs(self.enemies) do
        self:destroyEnemy(enemyId)
    end
    
    self.enemies = {}
    self.enemyCount = 0
    
    if self.debugMode then
        print("已清除所有敌人")
    end
end

-- 获取敌人数量
function EnemySpawner:getEnemyCount()
    local count = 0
    for _, enemy in pairs(self.enemies) do
        if enemy.data.isAlive then
            count = count + 1
        end
    end
    return count
end

-- 获取敌人列表
function EnemySpawner:getEnemies()
    return self.enemies
end

-- 根据ID获取敌人
function EnemySpawner:getEnemy(enemyId)
    return self.enemies[enemyId]
end

-- 对敌人应用伤害
function EnemySpawner:applyDamageToEnemy(enemyId, damage)
    local enemy = self.enemies[enemyId]
    if not enemy or not enemy.data.isAlive then return false end
    
    if self.debugMode then
        print(string.format("敌人 %s 受到 %d 点伤害 (原血量: %d)", enemyId, damage, enemy.data.health))
    end
    
    -- 应用伤害
    local isDead = false
    if enemy.aiSystem then
        isDead = enemy.aiSystem:applyDamage(damage, enemy.actionSystem)
    else
        enemy.data.health = math.max(0, enemy.data.health - damage)
        if enemy.data.health <= 0 then
            isDead = true
        end
    end
    
    if isDead then
        if self.debugMode then
            print("敌人死亡: " .. enemyId)
        end
        self:destroyEnemy(enemyId)
        return true
    end
    
    return false
end

-- 获取指定类型的敌人列表
function EnemySpawner:getEnemiesByType(enemyType)
    local enemiesOfType = {}
    for enemyId, enemy in pairs(self.enemies) do
        if enemy.type == enemyType and enemy.data.isAlive then
            table.insert(enemiesOfType, enemy)
        end
    end
    return enemiesOfType
end

-- 检查是否有敌人在攻击范围内
function EnemySpawner:hasEnemiesInAttackRange(playerPosition, attackRange)
    for _, enemy in pairs(self.enemies) do
        if enemy.data.isAlive then
            local distance = math.sqrt(
                (enemy.data.position.x - playerPosition.x) ^ 2 +
                (enemy.data.position.y - playerPosition.y) ^ 2
            )
            
            if distance <= attackRange then
                return true, enemy
            end
        end
    end
    return false, nil
end

-- 获取最近的敌人
function EnemySpawner:getNearestEnemy(position)
    local nearestEnemy = nil
    local minDistance = math.huge
    
    for _, enemy in pairs(self.enemies) do
        if enemy.data.isAlive then
            local distance = math.sqrt(
                (enemy.data.position.x - position.x) ^ 2 +
                (enemy.data.position.y - position.y) ^ 2
            )
            
            if distance < minDistance then
                minDistance = distance
                nearestEnemy = enemy
            end
        end
    end
    
    return nearestEnemy, minDistance
end

-- 设置敌人攻击性
function EnemySpawner:setEnemyAggression(enemyId, aggressionLevel)
    local enemy = self.enemies[enemyId]
    if enemy and enemy.aiSystem then
        enemy.aiSystem.aggressionLevel = aggressionLevel
        return true
    end
    return false
end

-- 重置所有敌人的攻击性
function EnemySpawner:resetAllEnemyAggression()
    for _, enemy in pairs(self.enemies) do
        if enemy.aiSystem then
            enemy.aiSystem.aggressionLevel = 1.0
        end
    end
end

-- 清理资源
function EnemySpawner:cleanup()
    self:clearAllEnemies()
    
    if self.enemyMovementSystem then
        self.enemyMovementSystem:reset()
        self.enemyMovementSystem = nil
    end
    
    self.spawnPositions = {}
    self.scene = nil
    self.playerEntity = nil
    
    if self.debugMode then
        print("敌人生成器已清理")
    end
end

-- 获取调试信息
function EnemySpawner:getDebugInfo()
    local info = {
        totalEnemies = self.enemyCount,
        aliveEnemies = self:getEnemyCount(),
        enemyTypes = {}
    }
    
    for enemyId, enemy in pairs(self.enemies) do
        if not info.enemyTypes[enemy.type] then
            info.enemyTypes[enemy.type] = 0
        end
        info.enemyTypes[enemy.type] = info.enemyTypes[enemy.type] + 1
    end
    
    return info
end

return EnemySpawner